package com.vinxin.app.boss.feign.config

import cn.hutool.core.util.StrUtil
import com.alibaba.fastjson2.JSONPath
import com.vinxin.app.exception.ResponseCodeEnum
import com.vinxin.app.exception.VXException
import feign.FeignException
import feign.Response
import feign.RetryableException
import feign.codec.ErrorDecoder
import java.nio.ByteBuffer
import java.nio.charset.StandardCharsets

class BossFeignErrorDecoder : ErrorDecoder {
    override fun decode(methodKey: String?, response: Response?): Exception {
        val exception = ErrorDecoder.Default().decode(methodKey, response)

        if (exception is RetryableException) {
            return exception
        }

        if (exception is FeignException && exception.responseBody().isPresent) {
            val responseBody: ByteBuffer = exception.responseBody().get()
            val bodyText: String = StandardCharsets.UTF_8.newDecoder().decode(responseBody.asReadOnlyBuffer()).toString()
            return VXException(
                ResponseCodeEnum.CROSS_SERVER_ERROR,
                StrUtil.format("HTTP request failed and error message is [{}].", JSONPath.eval(bodyText, "$.message"))
            )
        }
        return VXException(
            ResponseCodeEnum.CROSS_SERVER_ERROR, StrUtil.format("HTTP request failed with status code: {}", response?.status())
        )
    }
}